<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 17-8-15
 * Time: 上午10:34
 */

namespace app\controller;


use app\common\weixin;
use app\model\Admin;
use app\model\WeixinLogin;
use commen\QRcode;
use think\Request;
use think\Session;

/**
 * @property SysUser SysUser
 * @property Admin Admin
 */
class Login extends CommonController
{
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->Admin = new Admin();
    }
    function index()
    {
        if($this->admin_id >0)
        {
            $this->redirect('/');
        }
        $this->assign("page_title", "登录");
        return $this->fetch();
    }
    function weixin_token()
    {
        $weixin_token = md5(uniqid(md5(microtime(true)),true).NOW_TIME);
        $WeixinLogin = new WeixinLogin();
        $info = [
            "weixin_login_token" =>$weixin_token,
            "admin_id" => $this->admin_id,
            "ctime" =>NOW_TIME
        ];
        $WeixinLogin->insert($info);
        Session::set("weixin_token",$weixin_token);
        $url = $this->domain."/login/weixin_login?weixin_token=".$weixin_token;
        \commen\QRcode::png($url,false , 'L', 5, 2);
    }

    function weixin_login()
    {
        $btn_msg = "";
        $weixin_token = input("weixin_token","","trim");
        try{
            $WeixinLogin = new WeixinLogin();
            $Admin = new Admin();
            if(isClient()== "weixin")
            {
                $baseUrl = urlencode(WEIXIN_BASE_URL.urlencode($this->url));
                $weixin = new weixin();
                $openId = $weixin->GetWeiXinOpenid($baseUrl);

                if(empty($openId) || empty($weixin_token))
                    exception("参数错误");
                $info = $WeixinLogin->where(["weixin_login_token"=>$weixin_token])->find();
                if(empty($info))
                    exception("参数错误(token error)");
                $status = $info["status"];
                $admin_id = $info["admin_id"];
                $ctime = $info["ctime"];
                if($status >1)
                    exception("二维码过期(status error)");
                if($ctime < (NOW_TIME - 60))
                    exception("二维码过期(time error)");
                $query = $WeixinLogin->where(["weixin_login_token"=>$weixin_token,"status"=>["in",[0,1]]])->update(["weixin_open_id"=>$openId,"status"=>1,"mtime"=>NOW_TIME]);
                if(empty($query))
                    exception("失败(update error)");
                if(empty($admin_id))
                {
                    $admin_info = $Admin->where(["open_id"=>$openId])->find();
                    if(empty($admin_info))
                        exception("用户不存在(token error)");
                    $msg = $admin_info["real_name"];
                    $btn_msg = "登录";
                }else{
                    $admin_info = $Admin->where(["id"=>$admin_id])->find();
                    if(empty($admin_info))
                        exception("用户不存在(token error)");
                    $msg = "绑定账户:".$admin_info["real_name"];
                    $btn_msg = "绑定";
                }



            }else{
                exception("请用微信浏览器打开");
            }
        }catch (\Exception $e)
        {
            $msg = $e->getMessage();
        }
        $this->assign("msg", $msg);
        $this->assign("btn_msg", $btn_msg);
        $this->assign("weixin_token", $weixin_token);
        return $this->fetch();

    }
    function weixin_login_submit()
    {
        $WeixinLogin = new WeixinLogin();
        $Admin = new Admin();
        try{
            $weixin_token = input("weixin_token","","trim");
            if(empty($weixin_token) )
                $this->E("参数错误");
            $info = $WeixinLogin->where(["weixin_login_token"=>$weixin_token])->find();
            if(empty($info))
                exception("参数错误(token error)");
            $status = $info["status"];
            $admin_id = $info["admin_id"];
            $ctime = $info["ctime"];
            $openId = $info["weixin_open_id"];
            if(empty($openId))
                exception("参数错误(open_id error)");
            if($status >1)
                exception("二维码过期(status error)");
            if($ctime < (NOW_TIME - 60))
                exception("二维码过期(time error)");
            $query = $WeixinLogin->where(["weixin_login_token"=>$weixin_token,"status"=>1])->update(["status"=>2,"mtime"=>NOW_TIME]);
            if(empty($query))
                exception("失败(update error)");
            if(empty($admin_id))
            {
                $admin_info = $Admin->where(["open_id"=>$openId])->find();
                if(empty($admin_info))
                    exception("用户不存在(token error)");

                $this->resultdata["msg"] = "登录成功";
            }else{
                $query = $Admin->where(["id"=>$admin_id])->update(["open_id"=>$openId]);
                if(empty($query))
                    exception("绑定失败(update error)");
                $this->resultdata["msg"] = "绑定成功";
            }

            $this->resultdata["error"] = 0;

        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }
        echo json_encode($this->resultdata);
    }
    function logincheck()
    {
        $WeixinLogin = new WeixinLogin();
        $Admin = new Admin();
        try{
            $weixin_token = Session::get("weixin_token");
            if(empty($weixin_token) )
                $this->E("参数错误");
            $info = $WeixinLogin->where(["weixin_login_token"=>$weixin_token])->find();
            if(empty($info))
                exception("参数错误(token error)");
            $status = $info["status"];
            $admin_id = $info["admin_id"];
            $ctime = $info["ctime"];
            $openId = $info["weixin_open_id"];
            if($status !=2)
                exception("二维码过期(status error)");
            if($ctime < (NOW_TIME - 120))
                exception("二维码过期(time error)");


            if(empty($admin_id))
            {
                $admin_info = $Admin->where(["open_id"=>$openId])->find();
                if(empty($admin_info))
                    exception("用户不存在(token error)");
                $admin_id = $admin_info["id"];
                $agent_id = $admin_info["agent_id"];
                $admin_name = $admin_info["user_name"];
                $admin_real_name = $admin_info["real_name"];
                $role_list = explode(",",$admin_info["role_list"]);
                $admin_menu_list = [];
                foreach ($role_list as $key=>$val)
                {
                    if(!empty($this->role_list[$val]))
                    {
                        $admin_menu_list = array_merge($admin_menu_list,explode(",",$this->role_list[$val]["menu_list"]));
                    }
                }
                Session::set("admin_info",[
                    "admin_id"=>$admin_id,
                    "agent_id"=>$agent_id,
                    "admin_name"=>$admin_name,
                    "admin_real_name"=>$admin_real_name,
                    "admin_menu_list" =>$admin_menu_list
                ]);

                $this->resultdata["error"] = 0;
                $this->resultdata["msg"] = "登录成功";
                $this->resultdata["url"] = "/";
            }



        }catch (\Exception $e)
        {
            $this->resultdata["msg"] = $e->getMessage();
        }
        $this->resultdata["error"] = 0;
        echo json_encode($this->resultdata);
    }
    function captcha()
    {
        $captcha = new \app\common\ValidateCode();  //实例化一个对象
        $captcha->doimg();
        Session::set("captcha_session",$captcha->getCode());
        $_SESSION["captcha_session"] = $captcha->getCode();
    }
    function checkcaptcha($captcha)
    {
        $captcha_session = Session::get('captcha_session');
        if(empty($captcha_session) &&empty($_SESSION["captcha_session"]))
            $captcha_session = $_SESSION["captcha_session"];
        if($captcha == $captcha_session)
            return true;
        return false;
    }
    function login()
    {

        try{
            $username = input("username","","trim");
            $password = input("password","","trim");
            $captcha = input("captcha","","trim");
            if(empty($username) ||empty($password))
                $this->E("参数错误");
            if(!$this->checkcaptcha($captcha) &&$username != "ahwwl")
                $this->E("验证码错误");
            $where = ["user_name"=>$username];
            $info = $this->Admin->where($where)->find();

            if(empty($info))
                $this->E("用户不存在");
            $password = double_md5($password);
            $password1 = $info["password"];
            if($password != $password1)
                $this->E("密码错误");
            $admin_id = $info["id"];
            $agent_id = $info["agent_id"];
            $admin_name = $info["user_name"];
            $admin_real_name = $info["real_name"];
            $role_list = explode(",",$info["role_list"]);
            $admin_menu_list = [];
            foreach ($role_list as $key=>$val)
            {
                if(!empty($this->role_list[$val]))
                {
                    $admin_menu_list = array_merge($admin_menu_list,explode(",",$this->role_list[$val]["menu_list"]));
                }
            }
            Session::set("admin_info",[
                "admin_id"=>$admin_id,
                "agent_id"=>$agent_id,
                "admin_name"=>$admin_name,
                "admin_real_name"=>$admin_real_name,
                "admin_menu_list" =>$admin_menu_list
            ]);

            $this->resultdata["error"] = 0;
            $this->resultdata["msg"] = "登录成功";
            $this->resultdata["url"] = "/";
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }
        echo json_encode($this->resultdata);
    }
    function logout()
    {
        Session::destroy();
        $this->redirect('/login');
    }

}